<!--
 * @FilePath     : /study_code/vue/activated_deactivated.html
 * @Description  : activated, deactivated 钩子
 * @Date         : 2025-05-02 07:51:36
 * @Author       : Fang YingGui
 * @LastEditors  : fangyinggui 18715384437@163.com
 * @LastEditTime : 2025-05-02 07:51:37
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>documentName</title>
    <link rel="stylesheet" href="" />
  </head>
  <body>
    <div id="app">
      <div>
        <keep-alive>
          <component :is="curCom" />
        </keep-alive>
      </div>
      <button @click="changeCom">切换组件</button>
    </div>

    <script src="/vue/dist/vue.min.js"></script>
    <script src="./common.js"></script>
    <script>
      // 自定义组件
      const myComponent1 = {
        data: function () {
          return {}
        },
        props: [],
        template: `<p>动态组件1</p>`,

        /**
         * @brief: 被 keep-alive 缓存的组件 激活时调用。
         * @return {*}
         */
        activated() {
          console.log('被 keep-alive 缓存的组件激活时 ---- 1')
        },

        /**
         * @brief: 被 keep-alive 缓存的组件 失活时调用。
         * @return {*}
         */
        deactivated() {
          console.log('被 keep-alive 缓存的组件失活时 ---- 1')
        },
        methods: {},
      }
      const myComponent2 = {
        data: function () {
          return {}
        },
        props: [],
        template: `<p>动态组件2</p>`,
        // 钩子函数
        activated() {
          console.log('被 keep-alive 缓存的组件激活时 ---- 2')
        },
        deactivated() {
          console.log('被 keep-alive 缓存的组件失活时 ---- 2')
        },
        methods: {},
      }

      var app = new Vue({
        el: '#app',
        data: function () {
          return {
            curCom: myComponent1,
          }
        },
        components: {
          myComponent1,
          myComponent2,
        },
        methods: {
          changeCom() {
            this.curCom === myComponent1
              ? (this.curCom = myComponent2)
              : (this.curCom = myComponent1)
          },
        },
      })
    </script>
  </body>
</html>
